package com.guarantee.server.config.mybatis;

import com.alibaba.druid.filter.Filter;
import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.spring.boot.autoconfigure.DruidDataSourceBuilder;
import com.alibaba.druid.wall.WallConfig;
import com.alibaba.druid.wall.WallFilter;
import com.guarantee.server.common.utils.ListUtils;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;

import javax.sql.DataSource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Description 数据源配置
 * @Author future
 * @Date 2019/5/13
 * @Version Copyright (c) 2019,北京乾元坤和科技有限公司 All rights reserved.
 */
@Configuration
public class DataSourceConfig {

    @Bean
    @Primary
    @ConfigurationProperties("spring.datasource.druid.master")
    public DataSource masterDataSource() {
        DruidDataSource dataSource = DruidDataSourceBuilder.create().build();
        WallConfig wallConfig = new WallConfig();
        wallConfig.setMultiStatementAllow(true);
        WallFilter wallFilter = new WallFilter();
        wallFilter.setConfig(wallConfig);
        List<Filter> filterList = ListUtils.newArrayList();
        filterList.add(wallFilter);
        dataSource.setProxyFilters(filterList);
        return dataSource;
    }

    @Bean
    @ConfigurationProperties("spring.datasource.druid.slave")
    public DataSource slave1DataSource() {
        DruidDataSource dataSource = DruidDataSourceBuilder.create().build();
        WallConfig wallConfig = new WallConfig();
        wallConfig.setMultiStatementAllow(true);
        WallFilter wallFilter = new WallFilter();
        wallFilter.setConfig(wallConfig);
        List<Filter> filterList = ListUtils.newArrayList();
        filterList.add(wallFilter);
        dataSource.setProxyFilters(filterList);
        return dataSource;
    }

//    @Bean("myRoutingDataSource")
//    public DataSource myRoutingDataSource(@Qualifier("masterDataSource") DataSource masterDataSource,
//                                          @Qualifier("slave1DataSource") DataSource slave1DataSource) {
//        Map<Object, Object> targetDataSources = new HashMap<>(2);
//        targetDataSources.put(DBTypeEnum.MASTER, masterDataSource);
//        targetDataSources.put(DBTypeEnum.SLAVE, slave1DataSource);
//        MyRoutingDataSource myRoutingDataSource = new MyRoutingDataSource();
//        myRoutingDataSource.setDefaultTargetDataSource(masterDataSource);
//        myRoutingDataSource.setTargetDataSources(targetDataSources);
//        return myRoutingDataSource;
//    }

}
